// pages/recommendSong/recommendSong.js
import request from '../../../utils/request'
import PubSub from 'pubsub-js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    day: '',
    month: '',
    recommendDataList: [], // 每日推荐的数据
  },

  // 跳转至songDetail页面
  toSongDetail(event) {
    let id = event.currentTarget.id;
    wx.navigateTo({
      url: '/songPackage/pages/songDetail/songDetail?id=' + id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      // 去登陆
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          wx.reLaunch({
            url: '/pages/login/login',
          })
        }
      })
    }
    // 更新日期的状态数据
    this.setData({
      day: new Date().getDate(),
      month: new Date().getMonth() + 1
    })
    // 获取每日推荐的数据
    this.getRecommendData();

    // 订阅消息
    PubSub.subscribe('selectSong', (msg, data) => {
      let {
        type,
        audioId
      } = data;
      let {
        recommendDataList
      } = this.data;

      let currentIndex = recommendDataList.findIndex(item => item.id === audioId * 1)

      // 不考虑找不到的情况了
      currentIndex = type === 'pre' ? currentIndex - 1 : currentIndex + 1

      if (currentIndex === -1) currentIndex = recommendDataList.length - 1
      if (currentIndex >= recommendDataList.length) currentIndex = 0
      
      let song = recommendDataList[currentIndex]

      // 发送消息给播放页面
      PubSub.publish('selectedSong', song.id)

    })
  },
  async getRecommendData() {
    let {
      recommend
    } = await request('/recommend/songs');
    this.setData({
      recommendDataList: recommend
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})